module rx(CLK,RSTN,RXD,DATA,IDLE);
input CLK,RSTN,RXD;output IDLE;
output[7:0] DATA;
wire CLK,RSTN,RXD;
reg[7:0] DATA,contain;
reg[7:0] cnt; //计数变量
reg[3:0] cnt1;
reg temp,receive,IDLE;		//中间变量

always@(posedge CLK or negedge RSTN) begin
	if(!RSTN) cnt1<=0;
	else begin
	temp<=RXD;							//时刻检测是否收到起始位
		if((~temp)&IDLE) 					//检测到起始位
			case(cnt1)
				8'd8:begin
					cnt1<=0;
				end
				default:begin
					cnt1<=cnt1+1'b1;
				end
			endcase
	end
end

always@(posedge CLK or negedge RSTN )
	if(!RSTN) 	begin
		IDLE<=1;
		receive<=0;
	end
	else begin
		if(cnt1==8'd7) begin
			receive<=1;					//	连续接收到8个0，即消除了干扰误接收
			IDLE<=0;
		end
		if(cnt==8'd144) begin
			receive<=0;		//接收到停止位，使receive标志置零，表示不再接收，接收完毕
			IDLE<=1;			//接收完成，线路空闲
		end
	end
	
always@(posedge CLK or negedge RSTN) begin
	if(!RSTN) begin
		DATA<=8'bzz;
		cnt<=0;
	end
	else
	if(receive) begin   							//连续接收到8个0，消除了干扰后准备接收数据
		case(cnt)
			8'd16:begin								//因为采样率是波特率的16倍，理论上还有8个周期的起始位0才是第一个数据
				contain[0]<=RXD;				//为了接受到准确，消除数据边缘误差还，需要再计数16个周期采样稳定数据
				cnt<=cnt+1'b1;
			end
			8'd32:begin
				contain[1]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd48:begin
				contain[2]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd64:begin
				contain[3]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd80:begin
				contain[4]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd96:begin
				contain[5]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd112:begin
				contain[6]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd128:begin
				contain[7]<=RXD;
				cnt<=cnt+1'b1;
			end
			8'd144:begin
				//receive<=0;		//接收到停止位，使receive标志置零，表示不再接收，接收完毕
				cnt<=0;
				//IDLE<=1;		//接收完成，线路空闲
				DATA<=contain;
			end
			default:begin
				cnt<=cnt+1'b1;
			end
		endcase
	end
end
endmodule
				










					